// 全局请求封装
const base_url = 'https://api.weijiashangejiance.com';
const timeout = 60000;

export default (params) => {
	let url = params.url;
	let method = params.method || "get";
	let data = params.data || {};
	let header = {
		'Content-Type': 'application/json;charset=UTF-8',
		'Authorization': uni.getStorageSync('token') || '',
	};


	// 如果是GET请求，将参数拼接到URL上
	if (method.toLowerCase() === 'get' && Object.keys(data).length > 0) {
		const queryString = Object.keys(data)
			.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)
			.join('&');
		url += (url.indexOf('?') === -1 ? '?' : '&') + queryString;
	}

	if (method.toLowerCase() == "post") {
		header = {
			'Content-Type': 'application/json'
		};
	}


	return new Promise((resolve, reject) => {
		uni.showLoading({
			mask: true,
			title: '加载中'
		})
		uni.request({
			url: base_url + url,
			method: method,
			header: header,
			data: method.toLowerCase() === 'get' ? {} : data, // GET请求不传data
			timeout,
			success(response) {
				const res = response;
				const res2 = res.data
				
				if (res.statusCode == 200 && !res2.Code) {
					resolve(res.data);
				} else {
					switch (res.statusCode) {
						case 401:
							uni.showModal({
								title: "提示",
								content: "请登录",
								showCancel: false,
								success() {
									setTimeout(() => {
										uni.navigateTo({
											url: "/pages/login/index",
										});
									}, 1000);
								},
							});
							break;
						case 404:
							uni.showModal({
								title: "提示",
								content: "请求的地址不存在",
							});
							break;
						default:
							uni.showModal({
								title: "提示",
								content: res2.Message,
							});
							break;
					}
				}
			},
			fail(err) {
				if (err.errMsg.indexOf('request:fail') !== -1) {
					uni.showToast({
						title: '网络异常',
						icon: "error",
						duration: 2000
					});
				} else {
					uni.showToast({
						title: '未知异常',
						duration: 2000
					});
				}
				reject(err);
			},
			complete() {
				uni.hideLoading();
			}
		});
	}).catch(() => {
		uni.hideLoading();
	});
};